import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "@/store"
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: 'home',
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('../views/Home.vue')
  },
  {
    path: '/free',
    name: 'free',
    component: () => import('../views/Free.vue')
  },
  {
    path: '/goods',
    name: 'goods',
    component: () => import('../views/Goods.vue')
  },
  {
    path: '/order',
    name: 'order',
    component: () => import('../views/Order.vue')
  },
  {
    path: '/user',
    name: 'user',
    component: () => import('../views/User.vue'),
    redirect: '/user/cart',
    children: [
      {
        path: 'cart',
        component: () => import('../components/user/Cart.vue'),
      }
    ]
  },
  {
    path: '/details',
    name: 'Details',
    component: () => import(/* webpackChunkName: "details" */ '../views/Details.vue')
  }
  ,
  {
    path: '*',
    name: 'Error',
    component: () => import(/* webpackChunkName: "error" */ '../views/Error.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

const routerPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return routerPush.call(this, location).catch(err => { })

};

//全局导航守卫
router.beforeEach((to, from, next) => {
  if (to.path == '/user') {
    let token = localStorage.getItem('x-auth-token')
    if (token) {
      next();
    } else {
      console.log("进入了这里");
      store.dispatch("showToast/asyncShowToast", {
        isshow: true,
        title: "你还没有登录！",
        type: "danger",
      })
      return
    }
  }
  next();
})



export default router
